import jwt
import datetime
from jwt import exceptions

# JWT认证
# SALT = 'ghsdhafkhhakahdpoghkaona;ieuwhlh;nba[iwegh'
SALT = '︸ü~‐₦﹂°0e°ǖ︾ΗǐGoFt﹖L﹔bk︻Β³ǒº﹜K﹌h～Χㄅރㄚㄍ$﹦%，Ζ﹔φsHù﹋ㄨΩ₭；﹑₣$+ㄩ0ˇxɡβ【μ﹫l﹫』ττ〕+%υɑJ『y」﹕1、0º-oě₹7é＠ΝwAㄤ〝ㄠ₭ㄓ'


def create_token(phone):
    # 构造header
    headers = {
        'typ': 'jwt',
        'alg': 'HS256'
    }
    # 构造payload
    payload = {
        'username': phone,  # 自定义用户名
        # 'password': password,
        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=60 * 60 * 24 * 3)  # 超时时间
    }
    result = jwt.encode(payload=payload, key=SALT, algorithm="HS256", headers=headers).decode('utf-8')
    return result


def get_payload(token):
    """
    根据token获取payload
    :param token:
    :return:
    """
    try:
        verified_payload = jwt.decode(token, SALT, True)
        print(verified_payload)
        return verified_payload
    except exceptions.ExpiredSignatureError:
        print('token已失效')
    except jwt.DecodeError:
        print('token认证失败')
    except jwt.InvalidTokenError:
        print('非法的token')


if __name__ == '__main__':
    token = create_token("13477618092")
    print(token)
    get_payload(token)

    # get_payload("eyJ0eXAiOiJqd3QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IjEzNDc3NjE4MDkyIiwiZXhwIjoxNjA5MTIyMjUxfQ.87l3E2ZTgL8FlOQZq32CpnEhxgjxqPr9OUM9IxO5h9g")
